package com.java1412.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author java1412
 * @since 2023-02-21 10:08
 */
@Component
public class MyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre"; // 在路由之前
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true; // 放行
    }

    // 过滤逻辑
    @Override
    public Object run() throws ZuulException {
        // 获取当前请求的上下文信息
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取请求对象
        HttpServletRequest request = ctx.getRequest();
        // 请求方式 >>>>>>  请求地址
        System.out.println(request.getMethod() + "  >>>>  " + request.getRequestURL().toString());
        // 令牌应该是放在请求头
        // 获取令牌
        // String accessToken = request.getParameter("token");
        String accessToken = request.getHeader("token");
        if (accessToken == null) {
            System.out.println("token是空的");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            } catch (Exception e) {
            }
            return null;
        }
        System.out.println("ok");
        return ctx;
    }
}
